<template>
  <div>
    <!-- 页面标题 -->
    <v-row class="mb-6">
      <v-col cols="12" md="6" class="d-flex justify-end align-center">
        <v-chip :color="statusColor" variant="elevated" class="me-3">
          {{ formattedDate }}
        </v-chip>
        <v-btn
          color="primary"
          prepend-icon="mdi-qrcode-scan"
          @click="openQRScanner"
        >
          {{ $t('afterSchoolTeacher.scanToEnterClass') }}
        </v-btn>
      </v-col>
    </v-row>

    <!-- 学生列表 -->
    <v-card>
      <v-card-title>
        托班学生管理
        <v-spacer></v-spacer>
        <v-text-field
          v-model="searchText"
          append-inner-icon="mdi-magnify"
          :label="$t('common.search')"
          variant="filled"
          single-line
          hide-details
          density="compact"
          style="max-width: 300px;"
        ></v-text-field>
      </v-card-title>
      
      <v-card-text>
        <v-row>
          <v-col
            v-for="student in filteredStudents"
            :key="student.id"
            cols="12"
            sm="6"
            md="4"
            lg="3"
          >
            <AfterSchoolStudentCard
              :student="student"
              :show-parent-info="true"
              :show-actions="true"
              @check-in="checkInStudent"
              @check-out="checkOutStudent"
              @edit-notes="handleEditNotes"
            />
          </v-col>
        </v-row>
        
        <div v-if="loading" class="text-center py-8">
          <v-progress-circular indeterminate color="primary"></v-progress-circular>
          <p class="mt-4">{{ $t('common.loading') }}</p>
        </div>
        
        <div v-if="!loading && filteredStudents.length === 0" class="text-center py-8">
          <v-icon size="64" color="grey">mdi-account-group-outline</v-icon>
          <p class="text-h6 mt-4">{{ $t('common.noData') }}</p>
        </div>
        
        <!-- 分页组件 -->
        <div v-if="!loading && totalItems > itemsPerPage" class="d-flex justify-center mt-6">
          <v-pagination
            v-model="currentPage"
            :length="Math.ceil(totalItems / itemsPerPage)"
            :total-visible="7"
            color="primary"
          ></v-pagination>
        </div>
      </v-card-text>
    </v-card>

    <!-- 二维码扫描对话框 -->
    <v-dialog v-model="qrDialog" max-width="500">
      <v-card>
        <v-card-title>
          <v-icon class="me-2">mdi-qrcode-scan</v-icon>
          {{ $t('student.scanQRCode') }}
        </v-card-title>
        
        <v-card-text>
          <div id="qr-reader" style="width: 100%;"></div>
          
          <v-divider class="my-4"></v-divider>
          
          <v-text-field
            v-model="manualCode"
            :label="$t('driver.enterStudentNameOrNo')"
            variant="filled"
            density="comfortable"
            append-inner-icon="mdi-magnify"
            @click:append-inner="searchByCode"
            @keyup.enter="searchByCode"
          ></v-text-field>
        </v-card-text>
        
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn variant="text" @click="closeQRScanner">{{ $t('common.close') }}</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- 备注编辑对话框 -->
    <v-dialog v-model="notesDialog.show" max-width="500">
      <v-card>
        <v-card-title>
          编辑备注 - {{ notesDialog.student?.student_name }}
        </v-card-title>
        
        <v-card-text>
          <v-textarea
            v-model="notesDialog.notes"
            label="备注内容"
            variant="filled"
            rows="4"
            counter="200"
            maxlength="200"
            placeholder="请输入备注信息..."
          ></v-textarea>
        </v-card-text>
        
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn variant="text" @click="closeNotesDialog">取消</v-btn>
          <v-btn color="primary" @click="saveNotes" :loading="notesDialog.loading">保存</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- 操作结果提示 -->
    <v-snackbar
      v-model="snackbar.show"
      :color="snackbar.color"
      :timeout="3000"
    >
      {{ snackbar.text }}
      <template v-slot:actions>
        <v-btn
          variant="text"
          @click="snackbar.show = false"
        >
          {{ $t('common.close') }}
        </v-btn>
      </template>
    </v-snackbar>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { useSocketStore } from '@/stores/socket'
import { useAuthStore } from '@/stores/auth'
import { format } from 'date-fns'
import AfterSchoolStudentCard from '@/components/AfterSchoolStudentCard.vue'

export default {
  name: 'AfterSchoolArrivalManagement',
  
  components: {
    AfterSchoolStudentCard
  },
  
  setup() {
    const { t } = useI18n()
    const socketStore = useSocketStore()
    const authStore = useAuthStore()
    
    // 数据状态
    const loading = ref(false)
    const students = ref([])
    const searchText = ref('')
    const qrDialog = ref(false)
    const manualCode = ref('')
    const currentPage = ref(1)
    const itemsPerPage = ref(20)
    const totalItems = ref(0)
    const snackbar = ref({
      show: false,
      text: '',
      color: 'success'
    })
    
    // 备注对话框状态
    const notesDialog = ref({
      show: false,
      loading: false,
      student: null,
      notes: ''
    })
    
    // 计算属性
    const formattedDate = computed(() => {
      return format(new Date(), 'yyyy年MM月dd日')
    })
    
    const statusColor = computed(() => {
      const hour = new Date().getHours()
      if (hour >= 14) return 'success'
      if (hour >= 8) return 'warning'
      return 'error'
    })
    
    const filteredStudents = computed(() => {
      if (!searchText.value) return students.value
      const query = searchText.value.toLowerCase()
      return students.value.filter(student => 
        student.student_name?.toLowerCase().includes(query) ||
        student.student_no?.toLowerCase().includes(query)
      )
    })
    
// 获取今日队列中的托班学生列表
const fetchStudents = async () => {
  loading.value = true
  try {
    // 使用WebSocket获取当日普通教师标记的本班级学生（包括已进班和待进班）
    socketStore.socket.emit('get-after-school-queue-students', {
      teacherId: authStore.user?.id,
      userRole: authStore.userRole,
      date: new Date().toISOString().split('T')[0]
    })
  } catch (error) {
    console.error('获取托班学生列表失败:', error)
    showSnackbar('获取学生列表失败', 'error')
    loading.value = false
  }
}
    
    // 学生进入托班
    const checkInStudent = async (student) => {
      try {
        // 检查当前时间是否允许操作
        const now = new Date()
        const currentHour = now.getHours()
        
        // 课后托班教师只能在放学后操作（14:00后）
        if (currentHour < 14) {
          showSnackbar('课后托班只能在14:00后进行操作', 'warning')
          return
        }
        
        // 使用WebSocket处理学生进班
        socketStore.socket.emit('after-school-check-in', {
          student_id: student.student_id,
          attendance_record_id: student.attendance_record_id,
          after_school_class_id: student.after_school_class_id,
          teacherId: authStore.user?.id,
          userRole: authStore.userRole
        })
        
      } catch (error) {
        console.error('学生进入托班失败:', error)
        showSnackbar('学生进班失败', 'error')
      }
    }
    
    // 学生离开托班
    const checkOutStudent = async (student) => {
      try {
        // 使用WebSocket处理学生离班
        socketStore.socket.emit('after-school-check-out', {
          student_id: student.student_id,
          attendance_record_id: student.attendance_record_id,
          after_school_class_id: student.after_school_class_id,
          teacherId: authStore.user?.id,
          userRole: authStore.userRole
        })
        
      } catch (error) {
        console.error('学生离开托班失败:', error)
        showSnackbar('学生离班失败', 'error')
      }
    }
    
    // 二维码扫描器实例
    const qrScanner = ref(null)
    
    // 打开二维码扫描器
    const openQRScanner = () => {
      qrDialog.value = true
      // 延迟初始化扫描器以确保DOM已渲染
      setTimeout(initQRScanner, 100)
    }
    
    // 关闭二维码扫描器
    const closeQRScanner = () => {
      if (qrScanner.value) {
        qrScanner.value.clear()
        qrScanner.value = null
      }
      qrDialog.value = false
      manualCode.value = ''
    }
    
    // 初始化二维码扫描器
    const initQRScanner = async () => {
      try {
        const { Html5QrcodeScanner } = await import('html5-qrcode')
        
        qrScanner.value = new Html5QrcodeScanner(
          'qr-reader',
          {
            qrbox: { width: 250, height: 250 },
            fps: 20
          },
          false
        )
        
        qrScanner.value.render(onScanSuccess, onScanFailure)
      } catch (error) {
        console.error('初始化二维码扫描器失败:', error)
        showSnackbar('二维码扫描器初始化失败', 'error')
      }
    }
    
    // 扫描成功回调
    const onScanSuccess = (decodedText) => {
      searchByCode(decodedText)
      closeQRScanner()
    }
    
    // 扫描失败回调
    const onScanFailure = (error) => {
      // 忽略扫描失败（通常是没有检测到二维码）
    }
    
    // 扫码后直接更新学生状态为已进班
    const searchByCode = async (code = manualCode.value) => {
      if (!code) {
        showSnackbar('请输入学号', 'warning')
        return
      }
      
      try {
        // 直接通过WebSocket更新学生状态为已进班
        socketStore.socket.emit('after-school-scan-check-in', {
          qrCode: code,
          teacherId: authStore.user?.id,
          userRole: authStore.userRole,
          notes: '扫码进班'
        })
        
        // 清空输入框并关闭扫描器
        if (qrDialog.value) {
          closeQRScanner()
        }
      } catch (error) {
        console.error('扫码进班失败:', error)
        showSnackbar('扫码进班失败', 'error')
      }
    }
    
    // 显示提示信息
    const showSnackbar = (text, color = 'success') => {
      snackbar.value = {
        show: true,
        text,
        color
      }
    }
    
    // 处理编辑备注
    const handleEditNotes = (student) => {
      notesDialog.value.student = student
      notesDialog.value.notes = student.notes || ''
      notesDialog.value.show = true
    }
    
    // 关闭备注对话框
    const closeNotesDialog = () => {
      notesDialog.value.show = false
      notesDialog.value.student = null
      notesDialog.value.notes = ''
      notesDialog.value.loading = false
    }
    
    // 保存备注
    const saveNotes = async () => {
      if (!notesDialog.value.student) return
      
      notesDialog.value.loading = true
      try {
        // 使用WebSocket更新学生备注
        socketStore.socket.emit('update-student-notes', {
          student_id: notesDialog.value.student.student_id,
          attendance_record_id: notesDialog.value.student.attendance_record_id,
          notes: notesDialog.value.notes,
          teacherId: authStore.user?.id,
          userRole: authStore.userRole
        })
        
        showSnackbar('备注保存成功', 'success')
        closeNotesDialog()
        fetchStudents() // 刷新学生列表
      } catch (error) {
        console.error('保存备注失败:', error)
        showSnackbar('保存备注失败', 'error')
      } finally {
        notesDialog.value.loading = false
      }
    }
    
// 设置WebSocket事件监听器
const setupSocketListeners = () => {
  // 监听托班学生数据
      socketStore.socket.on('after-school-queue-students-data', (data) => {
        students.value = data.students || []
        totalItems.value = data.total || 0
        loading.value = false
      })
      
      // 监听学生进班结果
      socketStore.socket.on('after-school-check-in-result', (data) => {
        if (data.success) {
          showSnackbar(
            `${data.studentName} 已成功进班`,
            'success'
          )
          fetchStudents() // 刷新学生列表
        } else {
          showSnackbar(data.message || '学生进班失败', 'error')
        }
      })
      
      // 监听扫码进班结果
      socketStore.socket.on('after-school-scan-check-in-result', (data) => {
        if (data.success) {
          showSnackbar(
            `${data.data?.student_name || '学生'} 扫码进班成功`,
            'success'
          )
          fetchStudents() // 刷新学生列表
        } else {
          showSnackbar(data.message || '扫码进班失败', 'error')
        }
      })
      
      // 监听学生离班结果
      socketStore.socket.on('after-school-check-out-result', (data) => {
        if (data.success) {
          showSnackbar(
            `${data.studentName} 已成功离班`,
            'success'
          )
          fetchStudents() // 刷新学生列表
        } else {
          showSnackbar(data.message || '学生离班失败', 'error')
        }
      })
      
      // 监听学生状态更新
      socketStore.socket.on('student-status-updated', () => {
        fetchStudents() // 刷新学生列表
      })
    }
    
// 清理WebSocket事件监听器
    const cleanupSocketListeners = () => {
      socketStore.socket.off('after-school-queue-students-data')
      socketStore.socket.off('after-school-check-in-result')
      socketStore.socket.off('after-school-scan-check-in-result')
      socketStore.socket.off('after-school-check-out-result')
      socketStore.socket.off('student-status-updated')
    }
    
    // 组件挂载时获取数据
    onMounted(() => {
      setupSocketListeners()
      fetchStudents()
    })
    
    // 组件卸载时清理监听器
    onUnmounted(() => {
      if (qrScanner.value) {
        qrScanner.value.clear()
      }
      cleanupSocketListeners()
    })
    
    return {
      loading,
      students,
      searchText,
      qrDialog,
      manualCode,
      currentPage,
      itemsPerPage,
      totalItems,
      snackbar,
      notesDialog,
      formattedDate,
      statusColor,
      filteredStudents,
      fetchStudents,
      checkInStudent,
      checkOutStudent,
      handleEditNotes,
      closeNotesDialog,
      saveNotes,
      openQRScanner,
      closeQRScanner,
      searchByCode
    }
  }
}
</script>

<style scoped>
/* 与普通教师界面保持一致的样式 */
.student-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

.status-chip {
  font-weight: 600;
}

/* 二维码扫描器样式 */
:deep(#qr-reader) {
  border: 2px dashed #ddd;
  border-radius: 8px;
}

:deep(#qr-reader__camera_selection) {
  margin-bottom: 16px;
}

:deep(#qr-reader__scan_region) {
  border-radius: 8px;
}
</style>